package com.cheetah.start.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cheetah.start.common.constant.SessionConst;
import com.cheetah.start.common.utils.MyServletUtil;
import com.cheetah.start.system.admin.domain.SysAdmin;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * mybatis-plus 实体类字段自动填充配置
 * fieldName 为实体类名称
 *
 * @author xjhmwj
 * @date 2021/1/8 10:50
 */
@Component
public class FieldFillConfig implements MetaObjectHandler {


    /**
     * 插入填充
     * 异步插入数据库的不要使用自动填充,因为获取不到 request
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        HttpServletRequest request = MyServletUtil.getRequest();
        SysAdmin admin = (SysAdmin) request.getSession().getAttribute(SessionConst.NAME);
        this.setFieldValByName("createBy", admin != null ? admin.getName() : "", metaObject);

    }

    /**
     * 更新填充
     * 异步更新数据库的不要使用自动填充,因为获取不到 request
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        HttpServletRequest request = MyServletUtil.getRequest();
        SysAdmin admin = (SysAdmin) request.getSession().getAttribute(SessionConst.NAME);
        this.setFieldValByName("updateBy", admin != null ? admin.getName() : "", metaObject);
    }
}
